<?php

namespace app\common\service;

use app\common\model\Config;
use OSS\OssClient;
use OSS\Core\OssException;
use think\Exception;

/**
 * 阿里云存储引擎 (OSS)
 * Class Qiniu
 * @package app\common\library\storage\engine
 */
class AliyunOssService
{
    private $config;
    private $file;

    /**
     * 构造方法
     * Aliyun constructor.
     * @param $config
     */
    public function __construct()
    {
        $config = Config::getInfo("storage_config");
        $this->config = $config;
    }

    public function upload($save_dir, $name = 'file')
    {
        // 接收上传的文件
        $this->file = request()->file($name);
        if (empty($this->file)) {
            throw new Exception('未找到上传文件的信息');
        }

        // 校验上传文件后缀
        $limit = array_merge(config('project.file_image'), config('project.file_video'));
        if (!in_array(strtolower($this->file->extension()), $limit)) {
            throw new Exception('不允许上传' . $this->file->extension() . '后缀文件');
        }

        try {

            $ossClient = new OssClient(
                $this->config['access_key'],
                $this->config['secret_key'],
                $this->config['domain'],
                true
            );

            $filePath = $save_dir . '/' . $this->buildSaveName();
            $ossClient->uploadFile(
                $this->config['bucket'],
                $filePath,
                $this->file->getRealPath()
            );

            return $filePath;
        } catch (OssException $e) {
            $this->error = $e->getMessage();
            return false;
        }
        return true;
    }

    /**
     * 生成保存文件名
     */
    private function buildSaveName()
    {
        // 要上传图片的本地路径
        $realPath = $this->file->getRealPath();
        // 扩展名
        $ext = pathinfo($this->file->getOriginalName(), PATHINFO_EXTENSION);
        // 自动生成文件名
        return date('YmdHis') . substr(md5($realPath), 0, 5)
            . str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT) . ".{$ext}";
    }
}
